import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { withRouter } from 'react-router';
import { gql, useQuery } from '@apollo/client';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import EmptyData from '../../../../components/empty/EmptyData';
import s from './Library.module.css';
import {
	getParams,
	searchStringParams,
} from '../../../../helpers/getUrlParams';
import HostSearchInput from '../../../../components/HostSearchInput';
import { CONTENT_KEYWORD_IDX_LABEL_MAP } from '../../../../../common/constants';
import { number } from '../../../../../common/formatter';
import Edit from './Edit';

function queryGQLBuilder() {
	return gql`
		query ($word: String) {
			dataPagination: explictKeywordCategoryList(word: $word)
				@rest(
					type: "ExplictKeywordCategory"
					path: "/kb/keywords?{args}"
					endpoint: "v2"
				) {
				custom_keywords_count
				system_keywords_count
				type
			}
		}
	`;
}

function Library({ className, location, history }) {
	const params = getParams();
	const [type, setType] = React.useState('empty')
	const [filter, setFilter] = React.useState(
		params || {
			word: '',
			page: 1,
			pageSize: 10,
		}
	);
	const { data, loading, refetch } = useQuery(queryGQLBuilder(), {
		variables: { word: filter.word },
	});
	const tableData = React.useMemo(() => {
		const { page, pageSize } = filter;
		return Array.isArray(data?.dataPagination)
			? data?.dataPagination?.slice((page - 1) * pageSize, page * pageSize)
			: [];
	}, [data, filter]);
	const handleSearch = word => {
		const search = searchStringParams({
			word: word,
			page: 1,
			pageSize: 10,
		});
		setFilter({ ...filter, word });
		history.replace(`/policy-manage/keyword-settings/library?${search}`);
	};

	const columns = React.useMemo(
		() => [
			{
				title: '类别',
				dataIndex: 'type',
				key: 'type',
				render: x => CONTENT_KEYWORD_IDX_LABEL_MAP[x] || x,
			},
			{
				title: '默认词库量',
				dataIndex: 'system_keywords_count',
				key: 'system_keywords_count',
				render: number,
			},
			{
				title: '自定义词库量',
				dataIndex: 'custom_keywords_count',
				key: 'custom_keywords_count',
				render: number,
			},
			{
				title: '操作',
				dataIndex: 'type',
				key: '__actions__',
				className: s.action,
				width: 100,
				// eslint-disable-next-line react/display-name
				render: type => {
					return (
						<div className={s.content}>
							<Edit className={s.btn} type={type} refetch={refetch}>
								查看
							</Edit>
						</div>
					);
				},
			},
		],
		[]
	);
	React.useEffect(() => {
		if (!loading) setType('img')
	}, [loading])
	return (
		<div className={cn(className, s.library)}>
			<div className={s.toolbox}>
				<HostSearchInput
					allowClear
					placeholder="请输入敏感词"
					value={filter.word}
					onChange={handleSearch}
				/>
			</div>
			<Table
				pro
				columns={columns}
				data={tableData}
				loading={loading}
				empty={<EmptyData type={type} className={s.nobor} />}
			/>
			<div className={s.mt1rem}>
				<span className={s.pgc}>
					共<span>{tableData?.length || 0}</span>类
				</span>
			</div>
			{tableData?.length > 10 && (
				<div className={s.daj}>
					<Pagination
						current={filter.page}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						total={tableData?.dataPagination?.length || 0}
						onChange={(page, pageSize) => {
							const obj = Object.assign({}, filter);
							obj.page = page;
							obj.pageSize = pageSize;
							setFilter(obj);
						}}
					/>
				</div>
			)}
		</div>
	);
}

Library.propTypes = {
	className: PropTypes.string,
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
};

Library.defaultProps = {
	className: s.url,
};

export default withRouter(Library);
